package com.cook.controller.user;

import com.cook.result.Result;
import com.cook.service.FollowsService;
import com.cook.vo.user.FollowVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/follows")
@Slf4j
public class FollowsController {

    @Autowired
    private FollowsService followsService;

    /**
     * 关注用户
     * @param followerId 关注者ID（当前用户）
     * @param followeeId 被关注者ID（要关注的人）
     * @return 操作结果
     */
    @PostMapping("/follow")
    public Result<Boolean> follow(@RequestParam Long followerId,
                                    @RequestParam Long followeeId) {
        log.info("发送关注请求: followerId={}, followeeId={}", followerId, followeeId);

        try {
            boolean success = followsService.follow(followerId, followeeId);
            if (success) {
                return Result.success("关注成功", true);
            } else {
                return Result.error(404, "关注关系不存在");
            }
        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("关注失败: ", e);
            return Result.error(500, "关注失败");
        }
    }

    /**
     * 取消关注
     * @param followerId 关注者ID（当前用户）
     * @param followeeId 被关注者ID（要取消关注的人）
     * @return 操作结果
     */
    @DeleteMapping("/unfollow")
    public Result<Boolean> unfollow(@RequestParam Long followerId,
                                    @RequestParam Long followeeId) {
        log.info("取消关注请求: followerId={}, followeeId={}", followerId, followeeId);

        try {
            boolean success = followsService.unfollow(followerId, followeeId);
            if (success) {
                return Result.success("取消关注成功", true);
            } else {
                return Result.error(404, "关注关系不存在");
            }
        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("取消关注失败: ", e);
            return Result.error(500, "取消关注失败");
        }
    }

    /**
     * 检查是否已关注
     * @param followerId 关注者ID
     * @param followeeId 被关注者ID
     * @return 是否已关注
     */
    @GetMapping("/check")
    public Result<Boolean> checkFollowing(@RequestParam Long followerId,
                                          @RequestParam Long followeeId) {
        log.info("检查关注关系: followerId={}, followeeId={}", followerId, followeeId);

        try {
            boolean isFollowing = followsService.isFollowing(followerId, followeeId);
            return Result.success(isFollowing);
        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("检查关注关系失败: ", e);
            return Result.error(500, "检查关注关系失败");
        }
    }

    /**
     * 分页查询关注列表
     */
    @GetMapping("/{userId}/following/page")
    public Result<Map<String, Object>> getFollowingListByPage(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {

        log.info("分页查询关注列表: userId={}, pageNum={}, pageSize={}", userId, pageNum, pageSize);

        try {
            List<FollowVO> followList = followsService.getFollowListByPage(userId, pageNum, pageSize);
            int totalCount = followsService.getFollowCount(userId);
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);

            Map<String, Object> result = Map.of(
                    "list", followList,
                    "pageNum", pageNum,
                    "pageSize", pageSize,
                    "totalCount", totalCount,
                    "totalPages", totalPages
            );

            return Result.success(result);

        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("分页查询关注列表失败: ", e);
            return Result.error(500, "分页查询关注列表失败");
        }
    }

    /**
     * 查询用户的粉丝列表
     */
    @GetMapping("/{userId}/followers")
    public Result<List<FollowVO>> getFollowerList(@PathVariable Long userId) {
        log.info("查询粉丝列表: userId={}", userId);

        try {
            List<FollowVO> followerList = followsService.getFollowerList(userId);
            return Result.success(followerList);

        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("查询粉丝列表失败: ", e);
            return Result.error(500, "查询粉丝列表失败");
        }
    }

    /**
     * 查询关注数量（我关注的人数）
     */
    @GetMapping("/{userId}/following/count")
    public Result<Integer> getFollowingCount(@PathVariable Long userId) {
        log.info("查询关注数量: userId={}", userId);

        try {
            int followingCount = followsService.getFollowCount(userId);
            return Result.success(followingCount); //

        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("查询关注数量失败: ", e);
            return Result.error(500, "查询关注数量失败");
        }
    }

    /**
     * 查询粉丝数量（关注我的人数）
     */
    @GetMapping("/{userId}/followers/count")
    public Result<Integer> getFollowerCount(@PathVariable Long userId) {
        log.info("查询粉丝数量: userId={}", userId);

        try {
            int followerCount = followsService.getFollowerCount(userId);
            return Result.success(followerCount);

        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("查询粉丝数量失败: ", e);
            return Result.error(500, "查询粉丝数量失败");
        }
    }
}
